package jsu.xnm.evelyn.exception;

import jsu.xnm.evelyn.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author xnm
 * @version 1.0
 */

/**
 * 全局异常处理（捕获使用了这两个注解的类上的异常）
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody //返回json数据
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获SQLIntegrityConstraintViolationException异常
     * 即unique字段重复添加异常（违反唯一约束）
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //异常信息如下
        //2025-03-26T20:08:05.164+08:00 ERROR 27900 --- [nio-8080-exec-3] j.x.e.exception.GlobalExceptionHandler   :
        // Duplicate entry 'zhangsan' for key 'employee.idx_username'
        log.error(ex.getMessage());

        //获取异常的详细信息
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2]+"已存在";
            return Result.error("400",msg);
        }
        return Result.error("400","未知错误");
    }

    /**
     * 捕获CustomException异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public Result exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return Result.error("400",ex.getMessage());
    }
}
